package com.gitee.ixtf.vertx.internal.converter

import com.gitee.ixtf.vertx.ParameterConverter
import io.vertx.core.buffer.Buffer
import io.vertx.core.eventbus.Message
import io.vertx.ext.web.RoutingContext
import java.nio.charset.StandardCharsets.UTF_8

object Body2StringParameterConverter : ParameterConverter<String?> {
  private fun convertBody(body: Any?): String =
      when (body) {
        is String -> body
        is ByteArray -> body.toString(UTF_8)
        is Buffer -> body.toString(UTF_8)
        else -> throw RuntimeException()
      }

  override suspend fun convert(message: Message<*>) = message.body()?.let { convertBody(it) }

  override suspend fun convert(rc: RoutingContext) =
      rc.body()?.run { if (isEmpty) null else asString() }
}
